import React from 'react';

import { useReducer } from 'react'
import Child1 from './Child1';
import Child2 from './Child2';

import contextObj from './context';
const { Provider } = contextObj

//01:  在函数组件外定义状态
const initstate = {
    count: 0,
    user: {
        name: "曹德旺",
        age: 20
    }
}
//02: 定义修改state 数据的reducer 纯函数
const reducer = (initstate, action) => {
    // 03: 注意: 一定不能直接去修改原state, 而是修改它的拷贝对象
    const newState = { ...initstate }; // 浅拷贝

    if (action.type == '+') {
        newState.count += action.payload
        return newState
    }
    if (action.type == '-') {
        newState.count -= action.payload
        return newState
    }
    // 没有修改返回原state
    return initstate
}

const Father = () => {
    //使用useReducer
    const [state, dispatch] = useReducer(reducer, initstate)
    console.log(useReducer(reducer, initstate));

    return (
        <div>
            {/* 自己玩自己 */}
            <p>
                <button onClick={() => dispatch({ type: '+', payload: 1 })}>+</button>
                <span>{state.count}</span>
                <button onClick={() => dispatch({ type: '-', payload: 1 })}>-</button>
            </p>
            {/* 后代玩自己 */}
            <Provider value={{ state, dispatch }}>
                <Child1></Child1>
                <Child2></Child2>
            </Provider>

        </div>
    );
}

export default Father;
